package com.xb.loan.encryptor.mina.handler;


import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

/**
 * Created by IntelliJ IDEA.
 * User: Song.Peng
 * Date: 2009-8-19
 * Time: 14:09:16
 */

public class ConfineServerHandler extends IoHandlerAdapter {
    // 最大连接数
    protected short maxNum = 0;
    // 计数
    protected short num = 0;

    @Override
    public void sessionCreated(IoSession ioSession) throws Exception {

        synchronized (this) {
            if (num++ >= maxNum) {
                ioSession.close(true);
            }
        }

    }

    @Override
    public void sessionOpened(IoSession ioSession) throws Exception {
        super.sessionOpened(ioSession);
    }

    @Override
    public void sessionClosed(IoSession ioSession) throws Exception {

        synchronized(this){
            --num;
        }

    }

    @Override
    public void sessionIdle(IoSession ioSession, IdleStatus idleStatus) throws Exception {
        if (ioSession.isConnected()) {
            ioSession.close(true);
        }
    }

    @Override
    public void exceptionCaught(IoSession ioSession, Throwable throwable) throws Exception {
        super.exceptionCaught(ioSession, throwable);
    }

    @Override
    public void messageReceived(IoSession ioSession, Object o) throws Exception {
        super.messageReceived(ioSession, o);
    }

    public short getMaxNum() {
        return maxNum;
    }

    public void setMaxNum(short maxNum) {
        this.maxNum = maxNum;
    }

}
